package club.xyes.zkh.ecommerce.service.listener.impl;

import club.xyes.zkh.ecommerce.commons.context.ApplicationConstants;
import club.xyes.zkh.ecommerce.commons.entity.*;
import club.xyes.zkh.ecommerce.commons.properties.WechatConfigurationProperties;
import club.xyes.zkh.ecommerce.commons.util.DateTimeUtil;
import club.xyes.zkh.ecommerce.service.WxFormIdService;
import club.xyes.zkh.ecommerce.service.listener.OnUserMembershipLevelChangedListener;
import club.xyes.zkh.ecommerce.wechat.dto.SendTemplateMsgResult;
import club.xyes.zkh.ecommerce.wechat.dto.TemplateMsgData;
import club.xyes.zkh.ecommerce.wechat.dto.WxAccessToken;
import club.xyes.zkh.ecommerce.wechat.service.WeChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Create by 郭文梁 2019/5/6 0006 16:24
 * OnUserMembershipLevelChangedListenerImpl
 * 用户会员等级变化监听器实现
 *
 * @author 郭文梁
 * @data 2019/5/6 0006
 */
@Component
@Slf4j
public class OnUserMembershipLevelChangedListenerImpl implements OnUserMembershipLevelChangedListener {
    private static final String NOTIFY_TEMPLATE_MSG_ID = "m6heGWGWvMniLKvTspEKsNThUuEqqy9cOqWyGSk8dws";
    private final WechatConfigurationProperties wechatConfigurationProperties;
    private final WeChatService weChatService;
    private final WxFormIdService wxFormIdService;

    @Autowired
    public OnUserMembershipLevelChangedListenerImpl(WechatConfigurationProperties wechatConfigurationProperties,
                                                    WeChatService weChatService,
                                                    WxFormIdService wxFormIdService) {
        this.wechatConfigurationProperties = wechatConfigurationProperties;
        this.weChatService = weChatService;
        this.wxFormIdService = wxFormIdService;
    }

    @Override
    public void onChanged(UserMembership userMembership,
                          User user,
                          Shop shop,
                          ShopMembershipLevel level,
                          ShopMembership membership) {
        try {
            sendNotifyMsg(userMembership, user, shop, level);
        } catch (IOException e) {
            log.warn("Unable to send Membership Level Changed notify msg:", e);
        }
    }

    /**
     * 发送通知信息
     *
     * @param level 会员信息
     */
    private void sendNotifyMsg(UserMembership userMembership, User user, Shop shop, ShopMembershipLevel level) throws IOException {
        String appId = wechatConfigurationProperties.getUserMicroProgramAppId();
        String secret = wechatConfigurationProperties.getUserMicroProgramSecret();
        String openId = user.getWxOpenId();
        WxFormId formId = wxFormIdService.popOne(appId, openId);
        if (formId == null) {
            log.warn("Could not send Membership level changed notify msg, because no formId cached!");
            return;
        }
        WxAccessToken accessToken = weChatService.getAccessToken(appId, secret);
        Map<String, Object> options = new HashMap<>(10);
        options.put("page", "pages/VIPcard/VIPcard");
        Map<String, TemplateMsgData> data = new HashMap<>(4);
        data.put("keyword1", new TemplateMsgData(level.getName()));
        data.put("keyword2", new TemplateMsgData(user.getName()));
        data.put("keyword3", new TemplateMsgData(DateTimeUtil.format(userMembership.getUpdateTime(), ApplicationConstants.DATE_TIME_FORMAT)));
        data.put("keyword4", new TemplateMsgData(shop.getName()));
        Map<String, String> miniProgram = new HashMap<>(2);
        miniProgram.put("pagepath", "pages/VIPcard/VIPcard");
        SendTemplateMsgResult sendTemplateMsgResult = weChatService.sendTemplateMsg(appId, accessToken, formId.getFormId(),
                NOTIFY_TEMPLATE_MSG_ID, openId, data, miniProgram, options);
        log.debug("Send template msg completed {}", sendTemplateMsgResult);
    }
}
